<template>
  <el-container>
    <div id="particles"></div>
    <el-header>
      <div class="head">
        <!-- <el-upload
          class="upload-demo"
          ref="upload"
          action="http://localhost:8181/upload"
          :on-success="successUpLoad"
          :show-file-list="false"
        > -->
        <el-button
          slot="trigger"
          type="warning"
          class="mybutton"
          @click="importBorder"
        >
          导入边界
        </el-button>
        <!-- </el-upload> -->

        <el-button
          type="warning"
          class="mybutton"
          @click="show_configertion = !show_configertion"
        >
          参数配置
        </el-button>
        <el-button type="warning" class="mybutton" @click="meshGeneration">
          网格生成
        </el-button>
        <el-button type="warning" class="mybutton" @click="meshTransform">
          网格转换
        </el-button>
        <el-button
          type="warning"
          class="mybutton"
          @click="show_tools = !show_tools"
        >
          工具箱
        </el-button>

        <el-button type="warning" class="mybutton" @click="clearScreen"
          >重置</el-button
        >
        <el-button type="warning" class="mybutton">下载</el-button>
      </div>
    </el-header>
    <el-container>
      <el-aside style="text-align: -webkit-right">
        <div class="meshConfiger" v-show="show_configertion">
          <span class="title" onselectstart="return false;">
            Edit Configuration
          </span>
          <el-divider></el-divider>
          <el-form
            :model="editConfiguration"
            size="medium "
            style="width: 200px; margin-top: 10px"
          >
            <el-form-item
              label="密度"
              prop="distance"
              :rules="[
                { required: false, message: '密度不能为空' },
                { type: 'number', message: '密度必须为数字值' },
              ]"
            >
              <el-input
                type="number"
                v-model.number="editConfiguration.distance"
                autocomplete="off"
                style="width: 160px"
              ></el-input>
            </el-form-item>

            <el-form-item label="算法">
              <el-select v-model="editConfiguration.value" style="width: 160px">
                <el-option
                  v-for="item in editConfiguration.algo"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                style="background-color: #0f1c70; border-color: #0f1c70"
                type="primary"
                @click="submitForm('mesh')"
              >
                提交
              </el-button>
              <el-button
                style="background-color: #0f1c70; border-color: #0f1c70"
                type="primary"
                @click="resetForm('mesh')"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-aside>
      <el-main>
        <canvas
          id="canvas"
          width="1200px"
          height="600px"
          class="canvas"
          ref="canvas"
          @mousemove="mouseMove"
          @mouseup="mouseUp"
          @dblclick="mousedbClick"
          @mousedown="mouseDown"
        ></canvas>
      </el-main>
      <el-aside>
        <!-- 整个大盒子 -->
        <div class="container" v-show="show_tools">
          <span class="title" onselectstart="return false;"> Tools</span>

          <el-divider></el-divider>
          <!-- 每个图标的小盒子 -->
          <div class="box" @click="handleDrawType('L')">
            <!-- 放图片的小盒子 -->
            <div class="img">
              <!-- 图标 -->
              <img src="../assets/icon/线.png" alt="" />
            </div>
          </div>

          <div class="box" @click="handleDrawType('S')">
            <div class="img">
              <img src="../assets/icon/tx-正方形.png" alt="" />
            </div>
          </div>

          <div class="box" @click="handleDrawType('P')">
            <div class="img">
              <img src="../assets/icon/draw-polygon.png" alt="" />
            </div>
          </div>

          <div class="box" @click="handleDrawType('C')">
            <div class="img">
              <img src="../assets/icon/圆.png" alt="" />
            </div>
          </div>

          <div class="box" @click="editPoint">
            <div class="img">
              <img src="../assets/icon/点.png" alt="" />
            </div>
          </div>

          <div class="box" @click="show_pointdistance = !show_pointdistance">
            <div class="img">
              <img src="../assets/icon/点密度.png" alt="" />
              <el-slider
                style="position: absolute; left: 90px; bottom: 2px"
                v-model="mesh.distance"
                vertical
                height="200px"
                v-show="show_pointdistance"
              >
              </el-slider>
            </div>
          </div>

          <el-divider></el-divider>

          <div class="box" @click="roaming">
            <div class="img">
              <img src="../assets/icon/手.png" alt="" />
            </div>
          </div>

          <div class="box" @click="editerControler">
            <div class="img">
              <img src="../assets/icon/选择.png" alt="" />
            </div>
          </div>

          <div class="box" @click="expand">
            <div class="img">
              <img src="../assets/icon/放大缩小_X.png" alt="" />
            </div>
          </div>

          <div class="box" @click="narrow">
            <div class="img">
              <img src="../assets/icon/放大缩小_Y.png" alt="" />
            </div>
          </div>

          <div class="box" @click="reSet">
            <div class="img">
              <img src="../assets/icon/全图.png" alt="" />
            </div>
          </div>

          <div class="box">
            <div class="img" @click="colorPicker">
              <img
                src="../assets/icon/颜色选择器.png"
                alt=""
                style="
                  pointer-events: none;
                  z-index: 2;
                  background-color: #efeeee;
                "
              />
              <el-color-picker
                size="mini"
                v-model="mesh.color"
                style="position: absolute; z-index: 1"
              ></el-color-picker>
            </div>
          </div>

          <div class="box" @click="show_distanceBar = !show_distanceBar">
            <div class="img">
              <img src="../assets/icon/笔粗细.png" alt="" />
              <el-slider
                style="position: absolute; left: 160px; bottom: 5px"
                vertical
                height="200px"
                v-show="show_distanceBar"
              >
              </el-slider>
            </div>
          </div>
          <div class="box" @click="test">
            <div class="img">
              <img src="../assets/icon/橡皮.png" alt="" />
            </div>
          </div>
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>
<script>
import { Switch } from "element-ui";
import Axios from "axios";
// import swal from "sweetalert";
export default {
  data() {
    return {
      // 绘制类型 线：L,多边形：P,圆：C
      geometryType: "",
      // 是否开始绘制
      blDraw: false,
      // 存储已绘制图形
      geometries: [],
      // 存储绘制过程中的点
      currentPoints: [],
      ctx: "",
      canvas: "",
      canvasHeight: "",
      canvasWidth: "",
      EPSILON: 1.0 / 1048576.0,
      algoTag: "0",
      transTag: "-1",
      // 网格生成密度
      distance: 40,
      // 返回的网格生成数据
      returnData: "",
      // 网格生成算法
      gmshAlgo: "",
      // 漫游变量
      roamingTag: false,
      roamStart: [],
      // 漫游参数[X方向位移, Y方向位移, X缩放系数, Y缩放系数]
      roamPar: [0, 0, 1, 1],
      testGeo: [100, 100, 200, 200],
      // 是否显示工具箱
      show_tools: true,
      show_configertion: true,
      show_distanceBar: false,
      show_pointdistance: false,
      editConfiguration: {
        distance: 40,
        algo: [
          { value: 0, name: "Delaunay" },
          { value: 1, name: "MeshAdapt" },
          { value: 2, name: "Automatic" },
          { value: 3, name: "Frontal-Delaunay" },
          { value: 4, name: "Initial Mesh Only" },
          { value: 5, name: "Delaunay for Quads" },
          { value: 6, name: "Packing of Parallelograms" },
          { value: 7, name: "Quadrangle" },
          { value: 8, name: "Voronoi" },
          { value: 9, name: "Hexagon" },
          { value: 10, name: "Square" },
        ],
        value: 0,
      },
      mesh: {
        distance: 20,
        value: {
          node: [],
          element: [],
          neighbor: [],
          elementIndex: [],
          boxIndex: {},
        },
        color: "#121f72",
      },
      demData: "",
      editerTag: false,
      singleEdit: false,
      editerElement: [], // 存储编辑范围内的单元
      editInfo: {}, // 网格编辑信息
      editPointTag: false,
      mouseDownTag: false,
      editnodeTag: 0, //编辑的点
    };
  },
  methods: {
    unique(arr) {
      var arr1 = []; // 新建一个数组来存放arr中的值
      for (var i = 0, len = arr.length; i < len; i++) {
        if (arr1.indexOf(arr[i]) === -1) {
          arr1.push(arr[i]);
        }
      }

      return arr1;
    },
    uniquePlus(arr) {
      // 新建一个数组来存放arr中的值
      var oridata = new Array();
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        oridata.push([arr[index][0], arr[index][1]]);
      }
      console.log("oridata", oridata);

      for (var i = 0; i < arr.length; i++) {
        let tempElement1 = [arr[i][0], arr[i][1]];
        for (var j = i + 1; j < arr.length; j++) {
          let tempElement2 = [arr[j][0], arr[j][1]];
          if (
            tempElement1[0] == tempElement2[0] &&
            tempElement1[1] == tempElement2[1]
          ) {
            arr.splice(j, 1);
            arr.splice(i, 1);
            i--;
            break;
          } else if (
            tempElement1[0] == tempElement2[1] &&
            tempElement1[1] == tempElement2[0]
          ) {
            arr.splice(j, 1);
            arr.splice(i, 1);
            i--;
            break;
          }
        }
      }

      console.log("arr", arr);
      return arr;
    },
    editerControler() {
      if (this.mesh.value.element.length != "") {
        this.editerTag = true;
        this.singleEdit = true;
      } else {
        swal({
          title: "出错啦!",
          text: "请先生成网格!",
          icon: "error",
          button: "OK",
        });
      }
    },
    renderDem() {
      let mesh = this.demData.element;

      let minX, maxX, minY, maxY, minZ, maxZ;
      let range = this.demData.range;

      minX = range[0];
      maxX = range[1];

      minY = range[2];
      maxY = range[3];

      minZ = range[4];
      maxZ = range[5];
      mesh.forEach((element) => {
        this.ctx.beginPath();

        this.ctx.fillStyle =
          "RGB(" +
          (element.Z - minZ) * (255 / (maxZ - minZ)) +
          "," +
          (element.Z - minZ) * (255 / (maxZ - minZ)) +
          "," +
          (element.Z - minZ) * (255 / (maxZ - minZ)) +
          ")";

        // if (element.Z >= 33 && element.Z < 221) {
        //   _this.ctx.fillStyle = "RGB(255, 0, 255)";
        // } else if (element.Z >= 221 && element.Z < 409) {
        //   _this.ctx.fillStyle = "RGB(0, 0, 255)";
        // } else if (element.Z >= 409 && element.Z < 602) {
        //   _this.ctx.fillStyle = "RGB(0, 255, 255)";
        // } else if (element.Z >= 602 && element.Z < 790) {
        //   _this.ctx.fillStyle = "RGB(0, 255, 0)";
        // } else if (element.Z >= 790 && element.Z < 983) {
        //   _this.ctx.fillStyle = "RGB(255, 255, 0)";
        // } else if (element.Z >= 983 && element.Z < 1171) {
        //   _this.ctx.fillStyle = "RGB(255, 128, 0)";
        // } else if (element.Z >= 1171 && element.Z <= 2067) {
        //   _this.ctx.fillStyle = "RGB(128, 0, 0)";
        // }

        let x0 = (element.X[0] - minX) * ((1200 - 50) / (maxX - minX)) + 25;
        let y0 = (element.Y[0] - minY) * ((600 - 50) / (maxY - minY)) + 25;

        this.ctx.moveTo(x0, y0);

        for (let i = 1; i < element.X.length; i++) {
          let x = (element.X[i] - minX) * ((1200 - 50) / (maxX - minX)) + 25;
          let y = (element.Y[i] - minY) * ((600 - 50) / (maxY - minY)) + 25;
          this.ctx.lineTo(x, y);
        }
        this.ctx.closePath();
        this.ctx.fill();
      });
    },
    importBorder() {
      this.getMeshTData("http://localhost:8181/getDemInfor", true);
    },
    reSet() {
      this.ctx.clearRect(
        -this.roamPar[0] / this.roamPar[2],
        -this.roamPar[1] / this.roamPar[3],
        this.canvasWidth / this.roamPar[2],
        this.canvasHeight / this.roamPar[3]
      );
      this.ctx.transform(1 / this.roamPar[2], 0, 0, 1 / this.roamPar[3], 0, 0);
      this.ctx.transform(1, 0, 0, 1, -this.roamPar[0], -this.roamPar[1]);
      this.roamPar[0] = 0;
      this.roamPar[1] = 0;
      this.roamPar[2] = 1;
      this.roamPar[3] = 1;
      this.renderData();
      this.renderGeometries();
    },
    colorPicker() {
      console.log(this.mesh.color);
    },
    submitForm(formName) {
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     alert("submit!");
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
      // this.getEditBorder();
      if (this.editerTag == false) {
        this.$message({
          showClose: true,
          message: "请开始编辑",
          type: "error",
        });
        return 0;
      }
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.buildNewTopology();

      // var editerGeometry = this.geometries[this.geometries.length - 1]
      //   .coordinates;

      // this.ctx.beginPath();
      // this.ctx.lineWidth = 2;
      // this.ctx.strokeStyle = "red";

      // this.ctx.moveTo(editerGeometry[0][0], editerGeometry[0][1]);
      // for (let j = 1; j < editerGeometry.length; j++) {
      //   this.ctx.lineTo(editerGeometry[j][0], editerGeometry[j][1]);
      // }
      // this.ctx.closePath();
      // this.ctx.stroke();
    },
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.ctx.clearRect(
        -this.roamPar[0] / this.roamPar[2],
        -this.roamPar[1] / this.roamPar[3],
        this.canvasWidth / this.roamPar[2],
        this.canvasHeight / this.roamPar[3]
      );

      /**绘制编辑范围外的网格单元 */
      var borderElement = this.editInfo.borderElement;
      var borderEdges = this.editInfo.borderEdges;
      console.log("borderEdges", borderEdges);
      var node = this.mesh.value.node;

      this.ctx.beginPath();
      this.ctx.strokeStyle = "Black";
      this.ctx.lineWidth = 1;
      for (let i = 0; i < this.mesh.value.element.length; i++) {
        if (this.editerElement.includes(i)) {
          continue;
        }
        const element = this.mesh.value.element[i];
        this.ctx.moveTo(element.X[0], element.Y[0]);
        for (let index = 1; index < element.X.length; index++) {
          this.ctx.lineTo(element.X[index], element.Y[index]);
        }
        this.ctx.closePath();
      }
      this.ctx.stroke();
      /**绘制编辑边界 */
      this.ctx.beginPath();
      this.ctx.strokeStyle = "green";
      this.ctx.lineWidth = 4;

      for (let i = 0; i < borderEdges.length; i++) {
        let ponint1 = [node[borderEdges[i][0]][0], node[borderEdges[i][0]][1]];
        let ponint2 = [node[borderEdges[i][1]][0], node[borderEdges[i][1]][1]];
        if (i == 0) {
          this.ctx.moveTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        } else {
          this.ctx.lineTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        }
      }
      this.ctx.closePath();
      this.ctx.stroke();
    },
    expand() {
      this.ctx.clearRect(
        -this.roamPar[0] / this.roamPar[2],
        -this.roamPar[1] / this.roamPar[3],
        this.canvasWidth / this.roamPar[2],
        this.canvasHeight / this.roamPar[3]
      );
      this.ctx.transform(1.5, 0, 0, 1.5, 0, 0);
      this.roamPar[2] = this.roamPar[2] * 1.5;
      this.roamPar[3] = this.roamPar[3] * 1.5;

      // 图形渲染
      this.ctx.beginPath();
      this.ctx.strokeStyle = "red";
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(0, 500);
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(500, 0);
      this.ctx.stroke();

      this.renderData();
      this.renderGeometries();
      this.renderDem();
      // this.getMeshTData("http://localhost:8181/demTohexagon", true);
      // this.getMeshTData("http://localhost:8181/getDemInfor", true);
    },
    narrow() {
      this.ctx.clearRect(
        -this.roamPar[0] / this.roamPar[2],
        -this.roamPar[1] / this.roamPar[3],
        this.canvasWidth / this.roamPar[2],
        this.canvasHeight / this.roamPar[3]
      );

      this.ctx.transform(0.8, 0, 0, 0.8, 0, 0);
      this.roamPar[2] = this.roamPar[2] * 0.8;
      this.roamPar[3] = this.roamPar[3] * 0.8;

      this.renderData();
      this.renderGeometries();
    },
    renderGeometries() {
      if (this.geometries.length < 0) {
        return null;
      }

      for (let i = 0; i < this.geometries.length; i++) {
        let geoType = this.geometries[i].type;
        let geoCoor = this.geometries[i].coordinates;

        let dotPath = new Path2D();
        this.ctx.beginPath();
        this.ctx.strokeStyle = this.geometries[i].color;
        switch (geoType) {
          case "P":
            for (let j = 0; j < geoCoor.length; j++) {
              let element2 = geoCoor[j];
              if (j == 0) {
                this.ctx.moveTo(element2[0], element2[1]);
              } else {
                this.ctx.lineTo(element2[0], element2[1]);
              }
              dotPath.moveTo(element2[0], element2[1]);
              dotPath.arc(element2[0], element2[1], 3, 0, 2 * Math.PI);
            }
            this.ctx.closePath();
            break;
          default:
            break;
        }
        this.ctx.stroke();
        this.ctx.beginPath();

        this.ctx.fillStyle = "RGB(255, 255, 255)";
        this.ctx.strokeStyle = "RGB(15, 28, 112)";
        this.ctx.stroke(dotPath);
        this.ctx.fill(dotPath);
      }
    },
    renderData() {
      if (this.mesh.value.element == "") {
        return null;
      }

      this.ctx.strokeStyle = "Black";
      this.ctx.lineWidth = 1;
      let element = this.mesh.value.element;
      let node = this.mesh.value.node;
      var elementIndex = this.mesh.value.elementIndex;

      elementIndex.forEach((tempelementindex) => {
        this.ctx.beginPath();
        this.ctx.moveTo(
          node[tempelementindex[0]][0],
          node[tempelementindex[0]][1]
        );
        for (let index = 1; index < tempelementindex.length; index++) {
          this.ctx.lineTo(
            node[tempelementindex[index]][0],
            node[tempelementindex[index]][1]
          );
        }
        this.ctx.closePath();
        this.ctx.stroke();
      });

      // element.forEach((element) => {
      //   this.ctx.beginPath();
      //   this.ctx.moveTo(element.X[0], element.Y[0]);
      //   for (let index = 1; index < element.X.length; index++) {
      //     this.ctx.lineTo(element.X[index], element.Y[index]);
      //   }
      //   this.ctx.closePath();
      //   this.ctx.stroke();
      // });
    },
    roaming() {
      this.roamingTag = true;
    },
    test() {
      // var _this = this;
      // axios.post("http://localhost:8181/tesInter").then(function (resp) {
      //   console.log("DEM信息！");
      //   _this.returnData = resp.data;
      //   console.log(resp.data);
      //   _this.ctx.transform(1 / 1000, 0, 0, 1 / 1000, 0, 0);
      //   _this.renderDEM();
      // });
      // 图形渲染
      this.ctx.beginPath();
      this.ctx.strokeStyle = "red";
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(0, 500);
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(500, 0);

      // 位移
      this.ctx.transform(1, 0, 0, 1, 10, 10);
      this.ctx.stroke();

      this.ctx.beginPath();
      this.ctx.strokeStyle = "green";
      this.ctx.transform(2, 0, 0, 2, 0, 0);
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(0, 500);
      this.ctx.moveTo(0, 0);
      this.ctx.lineTo(500, 0);

      // 位移

      this.ctx.stroke();
    },
    successUpLoad(response) {
      console.log(response);

      // // console.log(file, fileList);
      // console.log(event);
    },
    parSetting() {
      swal({
        title: "操作确认",
        text: "删除后，您将无法恢复此虚拟文件！",
        icon: "warning",
        buttons: true,
        dangerMode: true,
      }).then((willDelete) => {
        if (willDelete) {
          swal("噗！您的虚拟文件已被删除！", {
            icon: "success",
          });
        } else {
          swal("你的虚拟文件是安全的！");
        }
      });
    },
    openMesh() {
      var _this = this;
      axios.post("http://localhost:8181/getDemInfor").then(function (resp) {
        console.log("DEM信息！");
        _this.mesh.value = resp.data;
        console.log(resp.data);

        let node = resp.data.node;

        // DEM范围
        let demRange = resp.data.range;
        // 栅格数据长宽
        let rasterXLength = node[node.length - 1][0] - node[0][0];
        let rasterYLength = node[node.length - 1][1] - node[0][1];

        let xSize = resp.data.xsize;
        let ySize = resp.data.ysize;
        // 适配屏幕的点坐标
        let x1, y1, x2, y2, x3, y3, x4, y4;

        // DEM渲染
        // 根据高程分4段段着色
        var colorvalue1 = demRange[4] + (demRange[5] - demRange[4]) / 4;
        var colorvalue2 = demRange[4] + (demRange[5] - demRange[4]) / 2;
        var colorvalue3 = demRange[4] + ((demRange[5] - demRange[4]) * 3) / 4;
        var colorvalue4 = demRange[5];

        for (let i = 0; i < ySize - 1; i++) {
          for (let j = 0; j < xSize - 1; j++) {
            // 栅格单元坐标转化（适应屏幕）渲染
            x1 =
              (node[i * xSize + j][0] - node[0][0]) *
                ((1200 - 100) / rasterXLength) +
              50;
            y1 =
              (node[i * xSize + j][1] - node[0][1]) *
                ((500 - 100) / rasterYLength) +
              50;

            x2 =
              (node[i * xSize + j + 1][0] - node[0][0]) *
                ((1200 - 100) / rasterXLength) +
              50;
            y2 =
              (node[i * xSize + j + 1][1] - node[0][1]) *
                ((500 - 100) / rasterYLength) +
              50;

            x3 =
              (node[(i + 1) * xSize + j + 1][0] - node[0][0]) *
                ((1200 - 100) / rasterXLength) +
              50;
            y3 =
              (node[(i + 1) * xSize + j + 1][1] - node[0][1]) *
                ((500 - 100) / rasterYLength) +
              50;

            x4 =
              (node[(i + 1) * xSize + j][0] - node[0][0]) *
                ((1200 - 100) / rasterXLength) +
              50;
            y4 =
              (node[(i + 1) * xSize + j][1] - node[0][1]) *
                ((500 - 100) / rasterYLength) +
              50;

            _this.ctx.beginPath();

            // _this.ctx.fillStyle = "RGB(" + (node[i * xSize + j][2] - demRange[4]) * (255 / (demRange[5] -
            //     demRange[4])) +
            //   "," + (node[i * xSize + j][2] - demRange[4]) * (255 / (demRange[5] - demRange[4])) + "," + (node[i *
            //     xSize + j][2] - demRange[4]) * (255 / (demRange[5] - demRange[4])) + ")";

            // if (node[i * xSize + j][2] > demRange[4] && node[i * xSize + j][2] < colorvalue1) {
            //   _this.ctx.fillStyle = 'RGB(25, 82, 25)'
            // } else if (node[i * xSize + j][2] > colorvalue1 && node[i * xSize + j][2] < colorvalue2) {
            //   _this.ctx.fillStyle = 'RGB(13, 17, 255)'
            // } else if (node[i * xSize + j][2] > colorvalue2 && node[i * xSize + j][2] < colorvalue3) {
            //   _this.ctx.fillStyle = 'RGB(51, 255, 0)'
            // } else if (node[i * xSize + j][2] > colorvalue3 && node[i * xSize + j][2] < colorvalue4) {
            //   _this.ctx.fillStyle = 'RGB(128, 6, 0)'
            // }
            if (node[i * xSize + j][2] >= 33 && node[i * xSize + j][2] < 221) {
              _this.ctx.fillStyle = "RGB(255, 0, 255)";
            } else if (
              node[i * xSize + j][2] >= 221 &&
              node[i * xSize + j][2] < 409
            ) {
              _this.ctx.fillStyle = "RGB(0, 0, 255)";
            } else if (
              node[i * xSize + j][2] >= 409 &&
              node[i * xSize + j][2] < 602
            ) {
              _this.ctx.fillStyle = "RGB(0, 255, 255)";
            } else if (
              node[i * xSize + j][2] >= 602 &&
              node[i * xSize + j][2] < 790
            ) {
              _this.ctx.fillStyle = "RGB(0, 255, 0)";
            } else if (
              node[i * xSize + j][2] >= 790 &&
              node[i * xSize + j][2] < 983
            ) {
              _this.ctx.fillStyle = "RGB(255, 255, 0)";
            } else if (
              node[i * xSize + j][2] >= 983 &&
              node[i * xSize + j][2] < 1171
            ) {
              _this.ctx.fillStyle = "RGB(255, 128, 0)";
            } else if (
              node[i * xSize + j][2] >= 1171 &&
              node[i * xSize + j][2] <= 2067
            ) {
              _this.ctx.fillStyle = "RGB(128, 0, 0)";
            }

            _this.ctx.moveTo(x1, y1);
            _this.ctx.lineTo(x2, y2);
            _this.ctx.lineTo(x3, y3);
            _this.ctx.lineTo(x4, y4);
            _this.ctx.closePath();
            _this.ctx.fill();
          }
        }
      });
    },
    meshTransform() {
      // if (this.returnData == "") {
      //   this.$message({
      //     showClose: true,
      //     message: "请先生成网格",
      //     type: "error",
      //   });
      //   return 0;
      // }
      var _this = this;
      switch (this.transTag) {
        case "0":
          // 三角网转四边形网格
          console.log("三角网转四边形网格");

          axios
            .post("http://localhost:8181/triToQuads", this.gmshAlgo)
            .then(function (resp) {
              let tri = resp.data.element;
              _this.mesh.value = resp.data;
              _this.ctx.strokeStyle = "Black";

              _this.ctx.clearRect(0, 0, _this.canvasWidth, _this.canvasHeight);
              tri.forEach((element) => {
                _this.ctx.beginPath();
                _this.ctx.moveTo(element.X[0], element.Y[0]);
                _this.ctx.lineTo(element.X[1], element.Y[1]);
                _this.ctx.lineTo(element.X[2], element.Y[2]);
                if (element.X.length == 4) {
                  _this.ctx.lineTo(element.X[3], element.Y[3]);
                }
                _this.ctx.closePath();
                _this.ctx.stroke();
              });
            });

          break;
        case "1":
          console.log("四边形网格转三角网");

          let postdata = new Array();
          this.mesh.value.node.forEach((element) => {
            postdata.push({
              X: element[0],
              Y: element[1],
            });
          });
          axios
            .post("http://localhost:8181/quadsTodelaunay", postdata)
            .then(function (resp) {
              let tri = resp.data.element;

              _this.mesh.value = resp.data;

              _this.ctx.strokeStyle = "Black";
              console.log("转换后的数据：");
              console.log(_this.mesh.value);
              _this.ctx.beginPath();
              _this.ctx.strokeStyle = "red";
              tri.forEach((element) => {
                _this.ctx.moveTo(element.X[0], element.Y[0]);
                _this.ctx.lineTo(element.X[1], element.Y[1]);
                _this.ctx.lineTo(element.X[2], element.Y[2]);
                if (element.X.length == 4) {
                  _this.ctx.lineTo(element.X[3], element.Y[3]);
                }
                _this.ctx.closePath();
              });
              _this.ctx.stroke();
            });
          break;
        case "2":
          console.log("DEM转六边形");
          this.getMeshTData("http://localhost:8181/demTohexagon", true);
          break;
        case "3":
          // DEM  to Triangle
          console.log("DEM转三角网");
          this.getMeshTData("http://localhost:8181/demToTri", true);

          break;
        case "4":
          // DEM  to Voronoi
          console.log("DEM  to Voronoi");
          this.getMeshTData("http://localhost:8181/demtovoronoi", true);

          break;
        default:
          this.$message({
            showClose: true,
            message: "请选择网格转换算法",
            type: "error",
          });
          break;
      }
    },
    meshGeneration() {
      console.log("网格生成");
      switch (this.algoTag) {
        case "0":
          this.getMeshGData("http://localhost:8181/getDelauney");
          this.gmshAlgo = "del2d";
          break;
        case "1":
          this.getMeshGData("http://localhost:8181/getMeshAdapt");
          this.gmshAlgo = "meshadapt";
          break;
        case "2":
          this.getMeshGData("http://localhost:8181/getauto");
          this.gmshAlgo = "auto";
          break;
        case "3":
          this.getMeshGData("http://localhost:8181/getfront2d");
          this.gmshAlgo = "front2d";
          break;
        case "4":
          this.getMeshGData("http://localhost:8181/getinitial2d");
          this.gmshAlgo = "initial2d";
          break;
        case "5":
          this.getMeshGData("http://localhost:8181/getdelquad");
          this.gmshAlgo = "delquad";
          break;
        case "6":
          this.getMeshGData("http://localhost:8181/getpack");
          this.gmshAlgo = "pack";
          break;
        case "7":
          this.getMeshGData("http://localhost:8181/getquads");
          break;
        case "8":
          this.getMeshGData("http://localhost:8181/getvoronoi");
          break;
        case "9":
          this.getMeshGData("http://localhost:8181/gethexagon");
          break;
        case "10":
          this.getMeshGData("http://localhost:8181/getsquare");
          break;
        default:
          this.$message({
            showClose: true,
            message: "请选择网格生成算法",
            type: "error",
          });
          break;
      }
    },
    getMeshTData(path, filltag) {
      var _this = this;
      axios.get(path).then(function (resp) {
        console.log(resp.data);

        let mesh = resp.data.element;
        _this.demData = resp.data;
        let minX, maxX, minY, maxY, minZ, maxZ;
        let range = resp.data.range;

        minX = range[0];
        maxX = range[1];

        minY = range[2];
        maxY = range[3];

        minZ = range[4];
        maxZ = range[5];

        // 渲染
        //  渲染前清空画布
        _this.ctx.clearRect(0, 0, _this.canvasWidth, _this.canvasHeight);
        mesh.forEach((element) => {
          _this.ctx.beginPath();
          if (filltag) {
            _this.ctx.fillStyle =
              "RGB(" +
              (element.Z - minZ) * (255 / (maxZ - minZ)) +
              "," +
              (element.Z - minZ) * (255 / (maxZ - minZ)) +
              "," +
              (element.Z - minZ) * (255 / (maxZ - minZ)) +
              ")";

            // if (element.Z >= 33 && element.Z < 221) {
            //   _this.ctx.fillStyle = "RGB(255, 0, 255)";
            // } else if (element.Z >= 221 && element.Z < 409) {
            //   _this.ctx.fillStyle = "RGB(0, 0, 255)";
            // } else if (element.Z >= 409 && element.Z < 602) {
            //   _this.ctx.fillStyle = "RGB(0, 255, 255)";
            // } else if (element.Z >= 602 && element.Z < 790) {
            //   _this.ctx.fillStyle = "RGB(0, 255, 0)";
            // } else if (element.Z >= 790 && element.Z < 983) {
            //   _this.ctx.fillStyle = "RGB(255, 255, 0)";
            // } else if (element.Z >= 983 && element.Z < 1171) {
            //   _this.ctx.fillStyle = "RGB(255, 128, 0)";
            // } else if (element.Z >= 1171 && element.Z <= 2067) {
            //   _this.ctx.fillStyle = "RGB(128, 0, 0)";
            // }
          }

          let x0 = (element.X[0] - minX) * ((1200 - 50) / (maxX - minX)) + 25;
          let y0 = (element.Y[0] - minY) * ((600 - 50) / (maxY - minY)) + 25;

          _this.ctx.moveTo(x0, y0);

          for (let i = 1; i < element.X.length; i++) {
            let x = (element.X[i] - minX) * ((1200 - 50) / (maxX - minX)) + 25;
            let y = (element.Y[i] - minY) * ((600 - 50) / (maxY - minY)) + 25;
            _this.ctx.lineTo(x, y);
          }
          _this.ctx.closePath();
          if (filltag) {
            _this.ctx.fill();
          } else {
            _this.ctx.stroke();
          }
        });
        //*********************************************************** */
        // console.log(resp.data);

        // let mesh = resp.data.node;
        // let minX, maxX, minY, maxY, minZ, maxZ;
        // let range = resp.data.range;

        // minX = range[0];
        // maxX = range[1];

        // minY = range[2];
        // maxY = range[3];

        // minZ = range[4];
        // maxZ = range[5];

        // let cellLength = (maxX - minX) / resp.data.xsize;
        // // 渲染
        // //  渲染前清空画布
        // _this.ctx.clearRect(0, 0, _this.canvasWidth, _this.canvasHeight);
        // mesh.forEach((element) => {
        //   _this.ctx.beginPath();
        //   if (filltag) {
        //     // _this.ctx.fillStyle =
        //     //   "RGB(" +
        //     //   (element[2] - minZ) * (255 / (maxZ - minZ)) +
        //     //   "," +
        //     //   (element[2] - minZ) * (255 / (maxZ - minZ)) +
        //     //   "," +
        //     //   (element[2] - minZ) * (255 / (maxZ - minZ)) +
        //     //   ")";

        //     if (element[2] >= 33 && element[2] < 221) {
        //       _this.ctx.fillStyle = "RGB(255, 0, 255)";
        //     } else if (element[2] >= 221 && element[2] < 409) {
        //       _this.ctx.fillStyle = "RGB(0, 0, 255)";
        //     } else if (element[2] >= 409 && element[2] < 602) {
        //       _this.ctx.fillStyle = "RGB(0, 255, 255)";
        //     } else if (element[2] >= 602 && element[2] < 790) {
        //       _this.ctx.fillStyle = "RGB(0, 255, 0)";
        //     } else if (element[2] >= 790 && element[2] < 983) {
        //       _this.ctx.fillStyle = "RGB(255, 255, 0)";
        //     } else if (element[2] >= 983 && element[2] < 1171) {
        //       _this.ctx.fillStyle = "RGB(255, 128, 0)";
        //     } else if (element[2] >= 1171 && element[2] <= 2067) {
        //       _this.ctx.fillStyle = "RGB(128, 0, 0)";
        //     }
        //   }

        //   let x0 =
        //     (element[0] - cellLength / 2 - minX) *
        //       ((1200 - 100) / (maxX - minX)) +
        //     50;
        //   let y0 =
        //     (element[1] - cellLength / 2 - minY) *
        //       ((600 - 100) / (maxY - minY)) +
        //     50;

        //   let x1 =
        //     (element[0] + cellLength / 2 - minX) *
        //       ((1200 - 100) / (maxX - minX)) +
        //     50;
        //   let y1 =
        //     (element[1] - cellLength / 2 - minY) *
        //       ((600 - 100) / (maxY - minY)) +
        //     50;

        //   let x2 =
        //     (element[0] + cellLength / 2 - minX) *
        //       ((1200 - 100) / (maxX - minX)) +
        //     50;
        //   let y2 =
        //     (element[1] + cellLength / 2 - minY) *
        //       ((600 - 100) / (maxY - minY)) +
        //     50;

        //   let x3 =
        //     (element[0] - cellLength / 2 - minX) *
        //       ((1200 - 100) / (maxX - minX)) +
        //     50;
        //   let y3 =
        //     (element[1] + cellLength / 2 - minY) *
        //       ((600 - 100) / (maxY - minY)) +
        //     50;

        //   _this.ctx.moveTo(x0, y0);
        //   _this.ctx.lineTo(x1, y1);
        //   _this.ctx.lineTo(x2, y2);
        //   _this.ctx.lineTo(x3, y3);

        //   _this.ctx.closePath();
        //   if (filltag) {
        //     _this.ctx.fill();
        //   } else {
        //     _this.ctx.stroke();
        //   }
        // });
      });
    },
    getMeshGData(path) {
      console.log("请求数据");
      var _this = this;
      var geometriesborder = new Array();

      if (this.geometries.length <= 0) {
        swal("请绘制边界！", "", "error");
        return 0;
      }
      this.geometries[0].coordinates.forEach((element) => {
        geometriesborder.push({
          X: element[0],
          Y: element[1],
        });
      });

      var postdata_temp = {
        border: geometriesborder,
        distance: this.editConfiguration.distance,
      };
      console.log("请求参数");
      console.log(postdata_temp);

      axios.post(path, postdata_temp).then(function (resp) {
        _this.mesh.value = resp.data;
        console.log("返回数据");
        console.log("_this.mesh.value", _this.mesh.value);
        _this.returnData = resp.data;
        let neighbor = resp.data.neighbor;
        console.log(_this.returnData);
        // _this.ctx.clearRect(
        //   -_this.roamPar[0] / _this.roamPar[2],
        //   -_this.roamPar[1] / _this.roamPar[3],
        //   _this.canvasWidth,
        //   _this.canvasHeight
        // );
        _this.mesh.value.element.forEach((element, elementindex) => {
          _this.ctx.beginPath();
          _this.ctx.strokeStyle = "Black";
          _this.ctx.lineWidth = 1;
          _this.ctx.moveTo(element.X[0], element.Y[0]);
          for (let index = 1; index < element.X.length; index++) {
            _this.ctx.lineTo(element.X[index], element.Y[index]);
          }
          _this.ctx.closePath();
          _this.ctx.stroke();
        });
      });
    },
    testgeneration() {
      console.log("生成");
      var vertices = new Array();
      var borderList = this.geometries[0];
      console.log(borderList);
      var maxX = borderList[0][0];
      var minX = borderList[0][0];
      var minY = borderList[0][1];
      var maxY = borderList[0][1];
      var border = new Path2D();
      for (let i = 0; i < borderList.length; i++) {
        let element = borderList[i];
        if (i == 0) {
          border.moveTo(element[0], element[1]);
        }
        border.lineTo(element[0], element[1]);
        vertices.push(element);
        if (element[0] < minX) {
          minX = element[0];
        }
        if (element[0] > maxX) {
          maxX = element[0];
        }
        if (element[1] < minY) {
          minY = element[1];
        }
        if (element[1] > maxY) {
          maxY = element[1];
        }
      }
      border.closePath();

      var x, y;
      this.ctx.beginPath();
      this.ctx.fillStyle = "Black";
      for (let i = 0; i < 100; i++) {
        do {
          x = Math.random() * (maxX - minX) + minX;
          y = Math.random() * (maxY - minY) + minY;
        } while (!this.ctx.isPointInPath(border, x, y));

        vertices.push([x, y]);
        this.ctx.moveTo(x, y);
        this.ctx.arc(x, y, 2, 0, 2 * Math.PI);
      }

      this.ctx.fill();
      console.log("vertices");
      console.log(vertices);
      var triangles = this.triangulate(vertices);
      console.log("triangles");
      console.log(triangles);
      var i;
      for (i = triangles.length; i; ) {
        this.ctx.beginPath();
        this.ctx.lineWidth = 1;
        --i;
        this.ctx.moveTo(vertices[triangles[i]][0], vertices[triangles[i]][1]);
        --i;
        this.ctx.lineTo(vertices[triangles[i]][0], vertices[triangles[i]][1]);
        --i;
        this.ctx.lineTo(vertices[triangles[i]][0], vertices[triangles[i]][1]);
        this.ctx.closePath();
        this.ctx.stroke();
      }
    },
    handleDrawType(command) {
      switch (command) {
        case "L":
          this.geometryType = "L";
          break;
        case "P":
          this.geometryType = "P";
          break;
        case "C":
          this.geometryType = "C";
          break;
        case "S":
          this.geometryType = "S";
          break;
        default:
          break;
      }
      this.blDraw = true;
      this.singleEdit = false;
    },
    mouseMove(e) {
      // 绘制橡皮线
      let xScreen = e.offsetX;
      let yScreen = e.offsetY;
      let x = (e.offsetX - this.roamPar[0]) / this.roamPar[2];
      let y = (e.offsetY - this.roamPar[1]) / this.roamPar[3];

      if (this.blDraw && this.currentPoints.length > 0) {
        // 1.清空画布
        // 2.绘制当前图形
        this.ctx.clearRect(
          -this.roamPar[0] / this.roamPar[2],
          -this.roamPar[1] / this.roamPar[3],
          this.canvasWidth,
          this.canvasHeight
        );
        let tempPath = new Path2D();
        this.ctx.beginPath();
        // this.ctx.strokeStyle = "RGB(15, 28, 112)";
        this.ctx.strokeStyle = this.mesh.color;
        for (let i = 0; i < this.currentPoints.length; i++) {
          let tempPoint = this.currentPoints[i];
          if (i == 0) {
            this.ctx.moveTo(tempPoint[0], tempPoint[1]);
          } else {
            this.ctx.lineTo(tempPoint[0], tempPoint[1]);
          }
          // 绘制端点样式
          tempPath.moveTo(tempPoint[0], tempPoint[1]);
          tempPath.arc(tempPoint[0], tempPoint[1], 3, 0, 2 * Math.PI);
        }
        this.ctx.lineTo(x, y);
        this.ctx.stroke();

        tempPath.moveTo(x, y);
        tempPath.arc(x, y, 3, 0, 2 * Math.PI);
        // 端点样式填充弄
        this.ctx.beginPath();
        this.ctx.fillStyle = "RGB(255, 255, 255)";
        this.ctx.strokeStyle = "RGB(15, 28, 112)";
        this.ctx.stroke(tempPath);
        this.ctx.fill(tempPath);

        // 渲染图形
        this.renderData();
        this.renderGeometries();
      }

      // 漫游控制
      if (this.roamingTag && this.roamStart.length > 0) {
        let xLength = (xScreen - this.roamStart[0]) / this.roamPar[2];
        let yLength = (yScreen - this.roamStart[1]) / this.roamPar[3];

        this.ctx.clearRect(
          -this.roamPar[0] / this.roamPar[2],
          -this.roamPar[1] / this.roamPar[3],
          this.canvasWidth / this.roamPar[2],
          this.canvasHeight / this.roamPar[3]
        );

        this.ctx.transform(1, 0, 0, 1, xLength, yLength);

        this.roamPar[0] = this.roamPar[0] + xLength * this.roamPar[2];
        this.roamPar[1] = this.roamPar[1] + yLength * this.roamPar[3];
        // 图形渲染
        this.ctx.beginPath();
        this.ctx.strokeStyle = "red";
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(0, 500);
        this.ctx.moveTo(0, 0);
        this.ctx.lineTo(500, 0);
        this.ctx.stroke();

        // 渲染图形
        this.renderData();
        this.renderGeometries();
        // this.getMeshTData("http://localhost:8181/demTohexagon", true);
        // this.getMeshTData("http://localhost:8181/getDemInfor", true);
        // this.renderDem();
        this.roamStart = [e.offsetX, e.offsetY];
      }

      // 编辑点
      if (this.editPointTag) {
        var nearestElement = this.findNearestElement(e.offsetX, e.offsetY);

        if (nearestElement != null) {
          this.ctx.clearRect(
            -this.roamPar[0] / this.roamPar[2],
            -this.roamPar[1] / this.roamPar[3],
            this.canvasWidth,
            this.canvasHeight
          );
          this.renderData();
          this.renderGeometries();
          var pointPath1 = new Path2D();
          var pointPath2 = new Path2D();

          if (this.mouseDownTag) {
            pointPath1.arc(e.offsetX, e.offsetY, 4, 0, Math.PI * 2);
            pointPath2.arc(e.offsetX, e.offsetY, 2, 0, Math.PI * 2);
            this.ctx.beginPath();
            this.ctx.lineWidth = 1;
            this.ctx.fillStyle = "rgb(15, 28, 112)";
            this.ctx.fill(pointPath1);

            this.ctx.beginPath();
            this.ctx.fillStyle = "white";

            this.ctx.fill(pointPath2);

            this.mesh.value.node[this.editnodeTag][0] = e.offsetX;
            this.mesh.value.node[this.editnodeTag][1] = e.offsetY;

            // this.mesh.value.element[nearestElement].X[selectedPoint[1]] =
            //   e.offsetX;
            // this.mesh.value.element[nearestElement].Y[selectedPoint[1]] =
            //   e.offsetY;
          } else {
            var meshElementIndex = this.mesh.value.elementIndex;
            var meshElement = this.mesh.value.element;
            var meshNode = this.mesh.value.node;
            this.editnodeTag = meshElementIndex[nearestElement][0];

            var nearestElement_X = meshElement[nearestElement].X;
            var nearestElement_Y = meshElement[nearestElement].Y;

            var selectedPoint = [
              Math.pow(e.offsetX - nearestElement_X[0], 2) +
                Math.pow(e.offsetY - nearestElement_Y[0], 2),
              0,
            ];

            for (let index = 0; index < nearestElement_X.length; index++) {
              let tempSelectedPoint =
                Math.pow(e.offsetX - nearestElement_X[index], 2) +
                Math.pow(e.offsetY - nearestElement_Y[index], 2);

              if (tempSelectedPoint < selectedPoint[0]) {
                selectedPoint[0] = tempSelectedPoint;
                selectedPoint[1] = index;
              }
            }

            this.editnodeTag =
              meshElementIndex[nearestElement][selectedPoint[1]];

            pointPath1.arc(
              meshNode[this.editnodeTag][0],
              meshNode[this.editnodeTag][1],
              8,
              0,
              Math.PI * 2
            );
            pointPath2.arc(
              meshNode[this.editnodeTag][0],
              meshNode[this.editnodeTag][1],
              4,
              0,
              Math.PI * 2
            );
            this.ctx.beginPath();
            this.ctx.lineWidth = 1;
            this.ctx.fillStyle = "rgb(15, 28, 112)";
            this.ctx.fill(pointPath1);

            this.ctx.beginPath();
            this.ctx.fillStyle = "white";

            this.ctx.fill(pointPath2);
          }
        }
      }
    },
    mouseUp(e) {
      this.roamStart = [];
      this.roamingTag = false;
      if (this.editPointTag) {
        this.editPointTag = false;
      }
      this.mouseDownTag = false;
    },
    mouseDown(e) {
      // 开始绘制
      if (this.blDraw) {
        let x = (e.offsetX - this.roamPar[0]) / this.roamPar[2];
        let y = (e.offsetY - this.roamPar[1]) / this.roamPar[3];
        this.currentPoints.push([x, y]);
      }
      // 漫游控制
      if (this.roamingTag) {
        this.roamStart = [e.offsetX, e.offsetY];
      }

      if (this.singleEdit) {
        var meshElement = this.mesh.value.element;
        var nearestElement = this.findNearestElement(e.offsetX, e.offsetY);
        if (nearestElement != null) {
          var nearestElement_X = meshElement[nearestElement].X;
          var nearestElement_Y = meshElement[nearestElement].Y;
          this.ctx.beginPath();
          this.ctx.strokeStyle = "green";
          this.ctx.lineWidth = 4;

          for (let index = 0; index < nearestElement_X.length; index++) {
            if (index == 0) {
              this.ctx.moveTo(nearestElement_X[index], nearestElement_Y[index]);
            } else {
              this.ctx.lineTo(nearestElement_X[index], nearestElement_Y[index]);
            }
          }
          this.ctx.closePath();
          this.ctx.stroke();
        }
      }
      this.mouseDownTag = true;
    },
    mousedbClick(e) {
      if (this.blDraw) {
        // 删除双击产生的重复点
        this.currentPoints.pop();

        let startPoint = this.currentPoints[0];
        let endPoint = this.currentPoints[this.currentPoints.length - 1];

        switch (this.geometryType) {
          case "P":
            // 多边形闭合
            this.ctx.beginPath();
            this.ctx.strokeStyle = this.mesh.color;
            this.ctx.moveTo(endPoint[0], endPoint[1]);
            this.ctx.lineTo(startPoint[0], startPoint[1]);
            this.ctx.stroke();

            // 起始端点样式填充
            this.ctx.beginPath();
            let tempPath = new Path2D();
            tempPath.moveTo(startPoint[0], startPoint[1]);
            tempPath.arc(startPoint[0], startPoint[1], 3, 0, 2 * Math.PI);

            tempPath.moveTo(endPoint[0], endPoint[1]);
            tempPath.arc(endPoint[0], endPoint[1], 3, 0, 2 * Math.PI);
            this.ctx.fillStyle = "RGB(255, 255, 255)";
            this.ctx.strokeStyle = "RGB(15, 28, 112)";
            this.ctx.stroke(tempPath);
            this.ctx.fill(tempPath);

            // 复制当前多边形
            var tempgeo = new Array();
            this.currentPoints.forEach((element) => {
              tempgeo.push(element);
            });
            // 存储图形
            this.geometries.push({
              type: "P",
              coordinates: tempgeo,
              color: this.mesh.color,
            });
            break;

          default:
            break;
        }

        // 找出编辑范围，删除范围内的多边形
        if (this.editerTag) {
          console.log(
            "edite_geometries",
            this.geometries[this.geometries.length - 1]
          );
          // var testtri = [[801,170],[910,172],[856,194]];
          var boundary = this.findBoundary(
            this.geometries[this.geometries.length - 1].coordinates
          );

          var boxindex = this.mesh.value.boxIndex;
          var oriPoint = boxindex.startPoint;

          var xIndexMIN = Math.floor(
            (boundary[0] - oriPoint.x) / boxindex.precision
          );
          var yIndexMIN = Math.floor(
            (boundary[1] - oriPoint.y) / boxindex.precision
          );

          var xIndexMAX = Math.floor(
            (boundary[2] - oriPoint.x) / boxindex.precision
          );
          var yIndexMAX = Math.floor(
            (boundary[3] - oriPoint.y) / boxindex.precision
          );

          var element = this.mesh.value.element;
          for (let i = xIndexMIN; i <= xIndexMAX; i++) {
            for (let j = yIndexMIN; j <= yIndexMAX; j++) {
              var containIndex = j * boxindex.XLength + i;
              let contain = boxindex.boxes[containIndex];

              contain.forEach((elementindex) => {
                let x = element[elementindex].X;
                let y = element[elementindex].Y;

                // 绘制附近所有单元
                // this.ctx.beginPath();
                // this.ctx.lineWidth = 2;
                // this.ctx.strokeStyle = "red";

                var chosed = false;
                for (let index = 0; index < x.length; index++) {
                  var intersectTag;
                  if (index == 0) {
                    let templine1 = [
                      [x[0], y[0]],
                      [x[x.length - 1], y[x.length - 1]],
                    ];
                    intersectTag = this.isLineIntersectPolygon(
                      templine1,
                      this.geometries[this.geometries.length - 1].coordinates
                    );
                  } else {
                    let templine2 = [
                      [x[index], y[index]],
                      [x[index - 1], y[index - 1]],
                    ];

                    intersectTag = this.isLineIntersectPolygon(
                      templine2,
                      this.geometries[this.geometries.length - 1].coordinates
                    );
                  }

                  if (intersectTag == 1 || intersectTag == 2) {
                    this.editerElement.push(elementindex);
                    chosed = true;
                    break;
                  }
                }
                if (chosed) {
                  this.ctx.beginPath();

                  this.ctx.lineWidth = 2;
                  this.ctx.strokeStyle = "green";
                  this.ctx.moveTo(x[0], y[0]);
                  for (let index1 = 1; index1 < x.length; index1++) {
                    this.ctx.lineTo(x[index1], y[index1]);
                  }
                  this.ctx.closePath();
                  this.ctx.stroke();
                }

                // path.closePath();
                // if (this.ctx.isPointInPath(path, e.offsetX, e.offsetY)) {
                //   break;
                // }
              });
            }
          }
          // this.ctx.stroke();
          if (this.editerElement.length == 0) {
            console.log("没有包含单元");
          }
          this.editerElement = this.unique(this.editerElement);
        }

        // 清空当前图形，停止绘图
        this.currentPoints.length = 0;
        this.blDraw = false;
      }
    },
    clearScreen() {
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      // 初始化
      this.geometryType = "";
      this.geometries.length = 0;
      this.blDraw = false;
      this.mesh.value = "";
    },
    drawPoint(x, y) {
      // 绘制端点
      this.ctx.beginPath();
      this.ctx.fillStyle = "RGB(255, 255, 255)";
      this.ctx.strokeStyle = "RGB(15, 28, 112)";
      this.ctx.moveTo(e.offsetX, e.offsetY);
      this.ctx.arc(e.offsetX, e.offsetY, 3, 0, 2 * Math.PI);
      this.ctx.stroke();
      this.ctx.fill();
    },
    editPoint() {
      // 编辑点
      this.singleEdit = false;
      this.editPointTag = true;
    },
    // 三角网
    contains(tri, p) {
      /* Bounding box test first, for quick rejections. */
      if (
        (p[0] < tri[0][0] && p[0] < tri[1][0] && p[0] < tri[2][0]) ||
        (p[0] > tri[0][0] && p[0] > tri[1][0] && p[0] > tri[2][0]) ||
        (p[1] < tri[0][1] && p[1] < tri[1][1] && p[1] < tri[2][1]) ||
        (p[1] > tri[0][1] && p[1] > tri[1][1] && p[1] > tri[2][1])
      )
        return null;

      var a = tri[1][0] - tri[0][0],
        b = tri[2][0] - tri[0][0],
        c = tri[1][1] - tri[0][1],
        d = tri[2][1] - tri[0][1],
        i = a * d - b * c;

      /* Degenerate tri. */
      if (i === 0.0) return null;

      var u = (d * (p[0] - tri[0][0]) - b * (p[1] - tri[0][1])) / i,
        v = (a * (p[1] - tri[0][1]) - c * (p[0] - tri[0][0])) / i;

      /* If we're outside the tri, fail. */
      if (u < 0.0 || v < 0.0 || u + v > 1.0) return null;

      return [u, v];
    },
    triangulate(vertices, key) {
      var n = vertices.length,
        i,
        j,
        indices,
        st,
        open,
        closed,
        edges,
        dx,
        dy,
        a,
        b,
        c;

      /* 没有足够的点 */
      if (n < 3) {
        return [];
      }

      /* Slice out the actual vertices from the passed objects. (Duplicate the
       * array even if we don't, though, since we need to make a supertriangle
       * later on!) */

      vertices = vertices.slice(0);

      if (key) {
        for (i = n; i--; ) {
          vertices[i] = vertices[i][key];
        }
      }

      // 建立顶点索引数组，按顶点的x位置排序。如果x位置相等，则通过比较指标进行稳定的排序。
      indices = new Array(n);

      for (i = n; i--; ) {
        indices[i] = i;
      }

      // console.log(indices);
      indices.sort(function (i, j) {
        var diff = vertices[j][0] - vertices[i][0];
        return diff !== 0 ? diff : i - j;
      });
      // console.log(indices);

      // 找到超三角形(包含所有其他三角形)的顶点，并将它们附加到顶点数组的末尾
      st = this.supertriangle(vertices);
      vertices.push(st[0], st[1], st[2]);

      /* Initialize the open list (containing the supertriangle and nothing
       * else) and the closed list (which is empty since we havn't processed
       * any triangles yet). */
      // 初始化开链表(只包含超三角形)和闭链表(因为我们还没有处理任何三角形，所以它是空的)。
      open = [this.circumcircle(vertices, n + 0, n + 1, n + 2)];
      closed = [];
      edges = [];

      /* Incrementally add each vertex to the mesh. */
      //    递增地将每个顶点添加到网格中。
      for (i = indices.length; i--; edges.length = 0) {
        c = indices[i];

        /* For each open triangle, check to see if the current point is
         * inside it's circumcircle. If it is, remove the triangle and add
         * it's edges to an edge list. */
        // 对于每个开三角形，检查当前点是否在它的圆周内。如果是，删除三角形并将它的边添加到边列表中。
        for (j = open.length; j--; ) {
          /* If this point is to the right of this triangle's circumcircle,
           * then this triangle should never get checked again. Remove it
           * from the open list, add it to the closed list, and skip. */
          // 如果这个点在这个三角形的圆的右边，那么这个三角形就不会被检查了。从打开列表中删除它，将其添加到关闭列表中，然后跳过。
          dx = vertices[c][0] - open[j].x;
          if (dx > 0.0 && dx * dx > open[j].r) {
            closed.push(open[j]);
            open.splice(j, 1);
            continue;
          }

          /* If we're outside the circumcircle, skip this triangle. */
          // 如果在圆周外，跳过这个三角形。
          dy = vertices[c][1] - open[j].y;
          if (dx * dx + dy * dy - open[j].r > this.EPSILON) continue;

          /* Remove the triangle and add it's edges to the edge list. */
          // 删除三角形并将它的边添加到边列表中
          edges.push(
            open[j].i,
            open[j].j,
            open[j].j,
            open[j].k,
            open[j].k,
            open[j].i
          );
          open.splice(j, 1);
        }

        /* Remove any doubled edges. */
        this.dedup(edges);

        /* Add a new triangle for each edge. */
        for (j = edges.length; j; ) {
          b = edges[--j];
          a = edges[--j];
          open.push(this.circumcircle(vertices, a, b, c));
        }
      }

      /* Copy any remaining open triangles to the closed list, and then
       * remove any triangles that share a vertex with the supertriangle,
       * building a list of triplets that represent triangles. */
      for (i = open.length; i--; ) {
        closed.push(open[i]);
      }

      open.length = 0;
      // console.log("closed",closed);
      for (i = closed.length; i--; ) {
        if (closed[i].i < n && closed[i].j < n && closed[i].k < n) {
          open.push(closed[i].i, closed[i].j, closed[i].k);
        }
      }

      /* Yay, we're done! */
      return open;
    },
    supertriangle(vertices) {
      var xmin = Number.POSITIVE_INFINITY,
        ymin = Number.POSITIVE_INFINITY,
        xmax = Number.NEGATIVE_INFINITY,
        ymax = Number.NEGATIVE_INFINITY,
        i,
        dx,
        dy,
        dmax,
        xmid,
        ymid;

      for (i = vertices.length; i--; ) {
        if (vertices[i][0] < xmin) xmin = vertices[i][0];
        if (vertices[i][0] > xmax) xmax = vertices[i][0];
        if (vertices[i][1] < ymin) ymin = vertices[i][1];
        if (vertices[i][1] > ymax) ymax = vertices[i][1];
      }

      dx = xmax - xmin;
      dy = ymax - ymin;
      dmax = Math.max(dx, dy);
      xmid = xmin + dx * 0.5;
      ymid = ymin + dy * 0.5;

      return [
        [xmid - 20 * dmax, ymid - dmax],
        [xmid, ymid + 20 * dmax],
        [xmid + 20 * dmax, ymid - dmax],
      ];
    },
    circumcircle(vertices, i, j, k) {
      var x1 = vertices[i][0],
        y1 = vertices[i][1],
        x2 = vertices[j][0],
        y2 = vertices[j][1],
        x3 = vertices[k][0],
        y3 = vertices[k][1],
        fabsy1y2 = Math.abs(y1 - y2),
        fabsy2y3 = Math.abs(y2 - y3),
        xc,
        yc,
        m1,
        m2,
        mx1,
        mx2,
        my1,
        my2,
        dx,
        dy;

      /* Check for coincident points */
      if (fabsy1y2 < this.EPSILON && fabsy2y3 < this.EPSILON)
        throw new Error("Eek! Coincident points!");

      if (fabsy1y2 < this.EPSILON) {
        m2 = -((x3 - x2) / (y3 - y2));
        mx2 = (x2 + x3) / 2.0;
        my2 = (y2 + y3) / 2.0;
        xc = (x2 + x1) / 2.0;
        yc = m2 * (xc - mx2) + my2;
      } else if (fabsy2y3 < this.EPSILON) {
        m1 = -((x2 - x1) / (y2 - y1));
        mx1 = (x1 + x2) / 2.0;
        my1 = (y1 + y2) / 2.0;
        xc = (x3 + x2) / 2.0;
        yc = m1 * (xc - mx1) + my1;
      } else {
        m1 = -((x2 - x1) / (y2 - y1));
        m2 = -((x3 - x2) / (y3 - y2));
        mx1 = (x1 + x2) / 2.0;
        mx2 = (x2 + x3) / 2.0;
        my1 = (y1 + y2) / 2.0;
        my2 = (y2 + y3) / 2.0;
        xc = (m1 * mx1 - m2 * mx2 + my2 - my1) / (m1 - m2);
        yc =
          fabsy1y2 > fabsy2y3 ? m1 * (xc - mx1) + my1 : m2 * (xc - mx2) + my2;
      }

      dx = x2 - xc;
      dy = y2 - yc;
      return {
        i: i,
        j: j,
        k: k,
        x: xc,
        y: yc,
        r: dx * dx + dy * dy,
      };
    },
    dedup(edges) {
      var i, j, a, b, m, n;

      for (j = edges.length; j; ) {
        b = edges[--j];
        a = edges[--j];

        for (i = j; i; ) {
          n = edges[--i];
          m = edges[--i];

          if ((a === m && b === n) || (a === n && b === m)) {
            edges.splice(j, 2);
            edges.splice(i, 2);
            break;
          }
        }
      }
    },

    findBoundary(geo) {
      if (geo.length < 1) return null;
      // minx,miny,maxx,maxy
      var boundary = [Infinity, Infinity, -Infinity, -Infinity];
      geo.forEach((element) => {
        if (element[0] < boundary[0]) boundary[0] = element[0];
        if (element[1] < boundary[1]) boundary[1] = element[1];

        if (element[0] > boundary[2]) boundary[2] = element[0];
        if (element[1] > boundary[3]) boundary[3] = element[1];
      });
      return boundary;
    },

    /**
     * 线段和多边形关系判断
     * Point[x,y],
     * Line[Point1,Point2],
     * Polygon[Point1,Point2,Point3...],
     * return{0:无关联 1：相交2：包含}
     */
    isLineIntersectPolygon(line, polygon) {
      var point1 = line[0];
      var point2 = line[1];

      var mypath = new Path2D();
      mypath.moveTo(polygon[0][0], polygon[0][1]);
      for (let i = 1; i < polygon.length; i++) {
        let point = polygon[i];
        mypath.lineTo(point[0], point[1]);
      }
      mypath.closePath();

      var poinInPolygonNum = 0;
      if (this.ctx.isPointInPath(mypath, point1[0], point1[1]))
        poinInPolygonNum++;

      if (this.ctx.isPointInPath(mypath, point2[0], point2[1]))
        poinInPolygonNum++;

      if (poinInPolygonNum == 2) {
        // 两个点都在多边形内
        return 2;
      } else if (poinInPolygonNum == 1) {
        // 一个点在多边形内
        return 1;
      } else {
        //没有点在多边形内
        for (let i = 0; i < polygon.length - 1; i++) {
          const line2 = [polygon[i], polygon[i + 1]];
          if (this.isLineIntersectLine(line, line2)) return 1;
        }
        return 0;
      }
    },
    isLineIntersectLine(line1, line2) {
      var p0_x = line1[0][0];
      var p0_y = line1[0][1];
      var p1_x = line1[1][0];
      var p1_y = line1[1][1];

      var p2_x = line2[0][0];
      var p2_y = line2[0][1];
      var p3_x = line2[1][0];
      var p3_y = line2[1][1];

      var s02_x, s02_y, s10_x, s10_y, s32_x, s32_y, s_numer, t_numer, denom, t;
      s10_x = p1_x - p0_x;
      s10_y = p1_y - p0_y;
      s32_x = p3_x - p2_x;
      s32_y = p3_y - p2_y;

      denom = s10_x * s32_y - s32_x * s10_y;
      if (denom == 0)
        //平行或共线
        return false; // Collinear
      var denomPositive = denom > 0;

      s02_x = p0_x - p2_x;
      s02_y = p0_y - p2_y;
      s_numer = s10_x * s02_y - s10_y * s02_x;
      if (s_numer < 0 == denomPositive)
        //参数是大于等于0且小于等于1的，分子分母必须同号且分子小于等于分母
        return false; // No collision

      t_numer = s32_x * s02_y - s32_y * s02_x;
      if (t_numer < 0 == denomPositive) return false; // No collision

      if (
        Math.abs(s_numer) > Math.abs(denom) ||
        Math.abs(t_numer) > Math.abs(denom)
      )
        return false; // No collision
      // Collision detected

      return true;
    },

    /**
     * 将边界点首位相连，形成一个闭环
     */
    creatRing(pointsListori) {
      // 去重
      var pointsList = this.uniquePlus(pointsListori);
      // var pointsList = pointsListori;
      var pointRing = new Array(); // 新建一个数组来存放圆环

      // 添加圆环起点
      var startEdge = [pointsList[0][0], pointsList[0][1]];

      pointRing.push([startEdge[0], startEdge[1]]);

      pointsList.splice(0, 1);

      var len = pointsList.length;

      for (let i = 0; i < len; i++) {
        var tempEdge = pointsList[i];
        if (startEdge[1] == tempEdge[0]) {
          pointRing.push([tempEdge[0], tempEdge[1]]);
          startEdge[0] = tempEdge[0];
          startEdge[1] = tempEdge[1];
          pointsList.splice(i, 1);
          i = -1;
          len = pointsList.length;
        } else if (startEdge[1] == tempEdge[1]) {
          pointRing.push([tempEdge[1], tempEdge[0]]);
          startEdge[0] = tempEdge[1];
          startEdge[1] = tempEdge[0];
          pointsList.splice(i, 1);
          i = -1;
          len = pointsList.length;
        }
      }

      return pointRing;
    },

    /**
     * return{"borderElement": borderElement,"borderEdges": edgesNeighborRing}
     * borderElement:[elementindex1, elementindex2, elementindex3...]
     * borderEdges:[[point1,point2],[point2,point3]...[pointn,point1]]
     */
    getEditBorderbackup() {
      var node = this.mesh.value.node;
      var element = this.mesh.value.element;
      var neighbor = this.mesh.value.neighbor;
      var elementIndex = this.mesh.value.elementIndex;

      var edgesNeighbor = new Array();
      var editerElementNew = this.editerElement;

      var borderElement = new Array(); //存储边界单元

      for (let i = 0; i < editerElementNew.length; i++) {
        const Index = editerElementNew[i];

        let neighborId = neighbor[Index];

        let x = element[Index].X;
        let y = element[Index].Y;

        let neighborNodes = new Array();

        neighborId.forEach((elementneighborId) => {
          if (editerElementNew.includes(elementneighborId)) {
            neighborNodes.push(elementIndex[elementneighborId]);
          }
        });

        if (neighborNodes.length < neighborId.length) {
          // 绘制边界单元
          // this.ctx.beginPath();
          // this.ctx.lineWidth = 2;
          // this.ctx.strokeStyle = "red";

          // this.ctx.moveTo(x[0], y[0]);
          // for (let j = 1; j < x.length; j++) {
          //   this.ctx.lineTo(x[j], y[j]);
          // }
          // this.ctx.closePath();
          // this.ctx.stroke();

          borderElement.push(Index);

          // 获取边界路径
          let currentNodes = new Array();
          currentNodes.push(elementIndex[Index][0]);
          currentNodes.push(elementIndex[Index][1]);
          currentNodes.push(elementIndex[Index][2]);
          let count = [0, 0, 0];

          // this.ctx.beginPath();
          // this.ctx.strokeStyle = "green";
          // this.ctx.lineWidth = 4;

          if (neighborNodes.length == 1) {
            if (!neighborNodes[0].includes(currentNodes[0])) {
              edgesNeighbor.push([currentNodes[1], currentNodes[0]]);
              edgesNeighbor.push([currentNodes[0], currentNodes[2]]);
            } else if (!neighborNodes[0].includes(currentNodes[1])) {
              edgesNeighbor.push([currentNodes[0], currentNodes[1]]);
              edgesNeighbor.push([currentNodes[1], currentNodes[2]]);
            } else {
              edgesNeighbor.push([currentNodes[1], currentNodes[2]]);
              edgesNeighbor.push([currentNodes[2], currentNodes[0]]);
            }
          } else {
            for (let j = 0; j < neighborNodes.length; j++) {
              if (neighborNodes[j].includes(currentNodes[0])) {
                count[0]++;
              }
              if (neighborNodes[j].includes(currentNodes[1])) {
                count[1]++;
              }
              if (neighborNodes[j].includes(currentNodes[2])) {
                count[2]++;
              }
            }

            if (count[0] == 2) {
              edgesNeighbor.push([currentNodes[1], currentNodes[2]]);
            } else if (count[1] == 2) {
              edgesNeighbor.push([currentNodes[0], currentNodes[2]]);
            } else {
              edgesNeighbor.push([currentNodes[0], currentNodes[1]]);
            }
          }
        }
      }

      // 绘制边界
      var edgesNeighborRing = this.creatRing(edgesNeighbor);
      this.ctx.beginPath();
      this.ctx.strokeStyle = "green";
      this.ctx.lineWidth = 4;

      for (let i = 0; i < edgesNeighborRing.length; i++) {
        let ponint1 = [
          node[edgesNeighborRing[i][0]][0],
          node[edgesNeighborRing[i][0]][1],
        ];
        let ponint2 = [
          node[edgesNeighborRing[i][1]][0],
          node[edgesNeighborRing[i][1]][1],
        ];
        if (i == 0) {
          this.ctx.moveTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        } else {
          this.ctx.lineTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        }
      }
      this.ctx.closePath();
      this.ctx.stroke();
      this.ctx.lineWidth = 1;
      return {
        borderElement: borderElement,
        borderEdges: edgesNeighborRing,
      };
    },
    getEditBorderCom() {
      var node = this.mesh.value.node;
      var element = this.mesh.value.element;
      var neighbor = this.mesh.value.neighbor;
      var elementIndex = this.mesh.value.elementIndex;

      var edgesNeighbor = new Array();
      var editerElementNew = this.editerElement;

      var borderElement = new Array(); //存储边界单元

      var editerGeometry =
        this.geometries[this.geometries.length - 1].coordinates;

      for (let i = 0; i < editerElementNew.length; i++) {
        const Index = editerElementNew[i];
        let neighborId = neighbor[Index];

        let x = element[Index].X;
        let y = element[Index].Y;
        // 绘制边界单元
        // this.ctx.beginPath();
        // this.ctx.lineWidth = 2;
        // this.ctx.strokeStyle = "red";

        // this.ctx.moveTo(x[0], y[0]);
        // for (let j = 1; j < x.length; j++) {
        //   this.ctx.lineTo(x[j], y[j]);
        // }
        // this.ctx.closePath();
        // this.ctx.stroke();

        let neighborNodes = new Array();

        neighborId.forEach((elementneighborId) => {
          if (editerElementNew.includes(elementneighborId)) {
            neighborNodes.push(elementIndex[elementneighborId]);
          }
        });

        if (neighborNodes.length < neighborId.length) {
          // 绘制边界单元
          // this.ctx.beginPath();
          // this.ctx.lineWidth = 2;
          // this.ctx.strokeStyle = "blue";

          // this.ctx.moveTo(x[0], y[0]);
          // for (let j = 1; j < x.length; j++) {
          //   this.ctx.lineTo(x[j], y[j]);
          // }
          // this.ctx.closePath();
          // this.ctx.stroke();

          borderElement.push(Index);

          // 获取边界路径
          let currentNodes = new Array();

          for (let j1 = 0; j1 < elementIndex[Index].length; j1++) {
            //形成开环
            var tempPoint1 = [
              node[elementIndex[Index][j1]][0],
              node[elementIndex[Index][j1]][1],
            ];
            var tempPoint2;
            if (j1 == elementIndex[Index].length - 1) {
              tempPoint2 = [
                node[elementIndex[Index][0]][0],
                node[elementIndex[Index][0]][1],
              ];
            } else {
              tempPoint2 = [
                node[elementIndex[Index][j1 + 1]][0],
                node[elementIndex[Index][j1 + 1]][1],
              ];
            }

            var line = [tempPoint1, tempPoint2];
            if (this.isLineIntersectPolygon(line, editerGeometry) == 0) {
              // this.ctx.beginPath();
              // this.ctx.lineWidth = 4;
              // this.ctx.strokeStyle = "green";

              // this.ctx.moveTo(tempPoint1[0], tempPoint1[1]);

              // this.ctx.lineTo(tempPoint2[0], tempPoint2[1]);

              // this.ctx.closePath();
              // this.ctx.stroke();

              if (j1 == elementIndex[Index].length - 1) {
                edgesNeighbor.push([
                  elementIndex[Index][j1],
                  elementIndex[Index][0],
                ]);
              } else {
                edgesNeighbor.push([
                  elementIndex[Index][j1],
                  elementIndex[Index][j1 + 1],
                ]);
              }
            }
          }

          // this.ctx.beginPath();
          // this.ctx.strokeStyle = "green";
          // this.ctx.lineWidth = 4;
        }
      }

      // 绘制边界
      console.log("edgesNeighbor", edgesNeighbor);
      var edgesNeighborRing = this.creatRing(edgesNeighbor);
      console.log("edgesNeighborRing", edgesNeighborRing);
      this.ctx.beginPath();
      this.ctx.strokeStyle = "green";
      this.ctx.lineWidth = 4;

      for (let i = 0; i < edgesNeighborRing.length; i++) {
        let ponint1 = [
          node[edgesNeighborRing[i][0]][0],
          node[edgesNeighborRing[i][0]][1],
        ];
        let ponint2 = [
          node[edgesNeighborRing[i][1]][0],
          node[edgesNeighborRing[i][1]][1],
        ];
        if (i == 0) {
          this.ctx.moveTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        } else {
          this.ctx.lineTo(ponint1[0], ponint1[1]);
          this.ctx.lineTo(ponint2[0], ponint2[1]);
        }
      }
      this.ctx.closePath();
      this.ctx.stroke();
      this.ctx.lineWidth = 1;
      return {
        borderElement: borderElement,
        borderEdges: edgesNeighborRing,
      };
    },
    buildNewTopology() {
      /**
       * 1.获取边界网格单元
       * 2.剔除边界网格单元中包含编辑区域单元的领接关系
       * 3.剔除箱式索引中包含编辑区域单元的索引
       * 4.建立新的拓扑关系
       */

      this.editInfo = this.getEditBorderCom();
      // var editInfo = this.getEditBorder();
      var borderElement = this.editInfo.borderElement;
      var borderEdges = this.editInfo.borderEdges;
      var node = this.mesh.value.node;

      this.ctx.beginPath();
      this.ctx.strokeStyle = "Black";
      this.ctx.lineWidth = 1;
      for (let i = 0; i < this.mesh.value.element.length; i++) {
        if (this.editerElement.includes(i)) {
          continue;
        }
        const element = this.mesh.value.element[i];
        this.ctx.moveTo(element.X[0], element.Y[0]);
        for (let index = 1; index < element.X.length; index++) {
          this.ctx.lineTo(element.X[index], element.Y[index]);
        }
        this.ctx.closePath();
      }
      this.ctx.stroke();

      var geometriesborder = new Array();
      for (let i = 0; i < borderEdges.length; i++) {
        geometriesborder.push({
          X: node[borderEdges[i][0]][0],
          Y: node[borderEdges[i][0]][1],
        });
      }

      var postdata_temp = {
        border: geometriesborder,
        distance: this.editConfiguration.distance,
      };

      console.log("网格编辑请求参数", postdata_temp);

      var _this = this;
      var postPath = "";
      console.log("this.editConfiguration.value", this.editConfiguration.value);

      switch (this.editConfiguration.value) {
        case 0:
          postPath = "http://localhost:8181/getDelauney";

          break;
        case 1:
          postPath = "http://localhost:8181/getMeshAdapt";

          break;
        case 2:
          postPath = "http://localhost:8181/getauto";

          break;
        case 3:
          postPath = "http://localhost:8181/getfront2d";

          break;
        case 4:
          postPath = "http://localhost:8181/getinitial2d";

          break;
        case 5:
          postPath = "http://localhost:8181/getdelquad";

          break;
        case 6:
          postPath = "http://localhost:8181/getpack";

          break;
        case 7:
          postPath = "http://localhost:8181/getquads";
          break;
        case 8:
          postPath = "http://localhost:8181/getvoronoi";
          break;
        case 9:
          postPath = "http://localhost:8181/gethexagon";
          break;
        case 10:
          postPath = "http://localhost:8181/getsquare";
          break;
      }

      axios.post(postPath, postdata_temp).then(function (resp) {
        let tri = resp.data.element;
        _this.returnData = resp.data;

        let neighbor = resp.data.neighbor;

        console.log("返回数据");
        console.log(_this.returnData);

        tri.forEach((element, elementindex) => {
          _this.ctx.beginPath();

          _this.ctx.strokeStyle = "red";
          _this.ctx.lineWidth = 1;

          _this.ctx.moveTo(element.X[0], element.Y[0]);
          for (let index = 1; index < element.X.length; index++) {
            _this.ctx.lineTo(element.X[index], element.Y[index]);
          }
          _this.ctx.closePath();
          _this.ctx.stroke();
        });
      });
    },
    findNearestElement(pointerX, pointerY) {
      var boxindex = this.mesh.value.boxIndex;
      var startPoint = boxindex.startPoint;
      var xIndex = Math.floor((pointerX - startPoint.x) / boxindex.precision);
      var yIndex = Math.floor((pointerY - startPoint.y) / boxindex.precision);

      var index = yIndex * boxindex.XLength + xIndex;

      //绘制背景四边形
      // this.ctx.beginPath();
      // this.ctx.strokeStyle = "red";
      // let squarStart = [
      //   startPoint.x + boxindex.precision * xIndex,
      //   startPoint.y + boxindex.precision * yIndex,
      // ];
      // this.ctx.moveTo(squarStart[0], squarStart[1]);
      // this.ctx.lineTo(squarStart[0] + boxindex.precision, squarStart[1]);
      // this.ctx.lineTo(
      //   squarStart[0] + boxindex.precision,
      //   squarStart[1] + boxindex.precision
      // );
      // this.ctx.lineTo(squarStart[0], squarStart[1] + boxindex.precision);
      // this.ctx.closePath();
      // this.ctx.stroke();

      let contain = boxindex.boxes[index];

      if (contain == undefined) {
        return null;
      }
      var element = this.mesh.value.element;
      this.ctx.beginPath();
      this.ctx.strokeStyle = "green";
      this.ctx.lineWidth = 4;
      for (let i = 0; i < contain.length; i++) {
        const elementindex = contain[i];
        let x = element[elementindex].X;
        let y = element[elementindex].Y;
        // this.ctx.beginPath();
        var path = new Path2D();
        path.moveTo(x[0], y[0]);

        // this.ctx.moveTo(x[0], y[0]);
        for (let index = 1; index < x.length; index++) {
          // this.ctx.lineTo(x[index], y[index]);
          path.lineTo(x[index], y[index]);
        }

        // this.ctx.closePath();

        path.closePath();
        if (this.ctx.isPointInPath(path, pointerX, pointerY)) {
          // this.ctx.stroke(path);
          return elementindex;
          break;
        }
      }

      // contain.forEach((elementindex) => {
      //   console.log(elementindex);
      //   let x = element[elementindex].X;
      //   let y = element[elementindex].Y;

      //   path = new Path2D();
      //   path.moveTo(x[0], y[0]);
      //   // this.ctx.moveTo(x[0], y[0]);
      //   for (let index = 1; index < x.length; index++) {
      //     // this.ctx.lineTo(x[index], y[index]);
      //     path.lineTo(x[index], y[index]);
      //   }

      //   // this.ctx.closePath();
      //   path.closePath();

      //   if (this.ctx.isPointInPath(path, e.offsetX, e.offsetY)) {
      //     break;
      //   }
      // });
      // this.ctx.stroke(path);
      // this.ctx.lineWidth = 1;

      // var date2 = new Date();
      // console.log(date2 - date1);

      return null;
    },
  },
  mounted() {
    //背景
    particlesJS.load("particles", "particles.json", function () {});
    //绘制
    // 1.获取画布
    this.canvas = this.$refs.canvas;
    // 2.获取 绘制工具箱
    this.ctx = this.canvas.getContext("2d");
    this.ctx.lineWidth = 1;
    this.ctx.strokeStyle = "black";

    // 3.获取画布尺寸
    this.canvasHeight = this.ctx.canvas.height;
    this.canvasWidth = this.ctx.canvas.width;

    // 绘制算法类型
    console.log("传递过来的参数");
    this.algoTag = this.$route.query.algotag;
    console.log(this.algoTag);
    switch (this.algoTag) {
      case "11":
        this.transTag = "0";
        this.algoTag = "0";
        break;
      case "12":
        this.transTag = "1";
        this.algoTag = "7";
        break;
      case "13":
        this.transTag = "2";
        this.algoTag = "-1";
        break;
      case "14":
        this.transTag = "3";
        this.algoTag = "-1";
        break;
      case "15":
        this.transTag = "4";
        this.algoTag = "-1";
      default:
        break;
    }
    console.log(this.algoTag);
    console.log(this.transTag);
    // 初始多边形;

    var tempgeo = new Array();
    tempgeo.push([50, 50]);
    tempgeo.push([1150, 50]);
    tempgeo.push([1150, 550]);
    tempgeo.push([50, 550]);

    // 存储图形;
    this.geometries.push({
      type: "P",
      coordinates: tempgeo,
      color: "#000000",
    });
    this.ctx.moveTo(tempgeo[0][0], tempgeo[0][1]);
    this.ctx.lineTo(tempgeo[1][0], tempgeo[1][1]);
    this.ctx.lineTo(tempgeo[2][0], tempgeo[2][1]);
    this.ctx.lineTo(tempgeo[3][0], tempgeo[3][1]);
    this.ctx.closePath();
    this.ctx.stroke();
  },
};
</script>
<style lang="less">
.el-color-picker__trigger {
  border: none;
}
.el-input__inner {
  padding-right: 0;
}
.meshConfiger {
  width: 220px;
  height: fit-content;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  align-items: center;
  background: #efeeee;
  margin-top: 20px;
  border-radius: 16px;

  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 10px;

  text-align: center;
}
.el-divider {
  margin-top: 5px;
  margin-bottom: 5px;
}
.title {
  width: 120px;
  text-align: center;
  margin-top: 10px;
  user-select: none;
  font-weight: bold;
  width: fit-content;
  // font-style: italic;
}
.container {
  width: 140px;
  height: fit-content;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  align-items: center;
  background: #efeeee;
  margin-top: 20px;
  border-radius: 16px;

  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 10px;
}
.container .box {
  display: flex;
  justify-content: space-around;
  flex-direction: column;
  align-items: center;
  align-content: center;
  width: 50px;
  height: 50px;
  margin: 5px;
}
.container .box .img {
  width: 50px;
  height: 50px;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.1),
    -5px -5px 10px rgba(255, 255, 255, 1);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #efeeee;
  transition: box-shadow 0.2s ease-out;
  position: relative;
}

.container .box .img img {
  width: 30px;
  transition: width 0.2s ease-out;
}
.container .box p {
  color: slategrey;
}
.container .box .img:hover {
  box-shadow: 0px 0px 0px rgba(0, 0, 0, 0.2),
    0px 0px 0px rgba(255, 255, 255, 0.8), inset 5px 5px 10px rgba(0, 0, 0, 0.1),
    inset -5px -5px 10px rgba(255, 255, 255, 1);
  transition: box-shadow 0.2s ease-out;
}
.container .box .img:hover img {
  width: 28px;
  transition: width 0.2s ease-out;
}

.particles-js-canvas-el {
  position: absolute;

  left: 0;
  right: 0;
  height: auto;
  min-height: 100%;
  background-image: initial;
  background-size: initial;
  background-attachment: initial;
  background-origin: initial;
  background-clip: initial;
  background-color: rgb(15, 28, 112);
  margin: auto;
}

.canvas {
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
  border-bottom-left-radius: 25px;
  // background-color: rgb(255, 255, 255);
  //   box-shadow: 10px 10px 5px #888888;
  margin: auto;
  background-color: #eff0f1;
  box-shadow: 0px 0px 2px #fffffff8;
}

.head {
  width: fit-content;
  height: 50px;
  margin: auto;
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  border-bottom-left-radius: 25px;
  border-bottom-right-radius: 25px;
  padding-left: 10px;
  padding-right: 10px;
  // background-color: white;

  // text-align: center;

  box-shadow: 0px 0px 2px #fffffff8;
}

.el-header {
  text-align: center;
  margin-top: 80px;
  margin-bottom: 10px;
  position: relative;
  // padding-top: 50px;
}

.el-dropdown {
  margin-left: 8px;
  margin-right: 8px;
}

.mybutton {
  margin-top: 2.5px;
  margin-left: 10px;
  margin-right: 10px;
  font-size: 18px;
  // align-self: center;
  // margin: auto;
}

.upload-demo {
  display: inline-block;
}
.el-main {
  text-align: center;
  position: relative;
  width: 1500px;
  // padding-top: 60px;
  //   line-height: 160px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
.el-aside {
  // margin: auto;
  position: relative;
  height: 520px;
}

.icon {
  padding-top: 5px;
  width: 30px;
  height: 30px;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>